import {
  Button,
  Divider,
  Form,
  FormItem,
  Input,
  notification,
  Space,
  Spin,
  Switch,
  Upload
} from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { commonApi, marketingApi } from '@/apis'
import {
  type ProEditorProps,
  type ProEditorRef,
  ProEditor,
  SvgIcon
} from '@/components'
import { useDialog } from '@/hooks'
import { useTabsStore } from '@/store'

import styles from './index.module.css'

type UploadKey = 'indexPicture' | 'bannerPicture'

const { useForm } = Form

export default defineComponent({
  name: 'GroupConfig',
  setup() {
    const loading = ref(false)
    const formModel = ref({
      status: 0,
      title: '',
      groupRule: '',
      indexPicture: '',
      bannerPicture: ''
    })
    const formRules = ref({
      title: [{ required: true, message: '请输入' }],
      groupRule: [{ required: true, message: '请输入' }],
      indexPicture: [{ required: true, message: '请上传' }],
      bannerPicture: [{ required: true, message: '请上传' }]
    } as FormRules)
    const editorRef = ref({} as ProEditorRef)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '300px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data

              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)
    const fileList = ref({
      indexPicture: [] as any[],
      bannerPicture: [] as any
    })

    const tabsStore = useTabsStore()
    const route = useRoute()
    const router = useRouter()
    const formRef = useForm(formModel, formRules)
    const { showConfirm } = useDialog()

    /** 上传 */
    function handleUploadChange(key: UploadKey, params: FileInfo) {
      fileList.value[key] = params.fileList

      if (params.file.status === 'done') {
        formModel.value[key] = params.file.response.data
      }
    }

    /** 移除 */
    function handleRemoveUpload(key: UploadKey, params: FileItem) {
      formModel.value[key] = ''
      fileList.value[key] = []
    }

    /** 取消 */
    function handleCancel() {
      showConfirm({
        content: '确认取消修改？',
        onOk: () => {
          tabsStore.delCachedTab(route).then(() => {
            const { fullPath } = route

            nextTick(() => {
              router.replace({
                path: '/redirect' + fullPath
              })
            })
          })
        }
      })
    }

    /** 提交 */
    function handleSubmit() {
      const editorText = editorRef.value.editor.getText()
      const editorHtml = editorRef.value.editor.getHtml()

      formModel.value.groupRule = editorText
        ? editorHtml
        : editorHtml.includes('<img')
        ? editorHtml
        : ''

      nextTick(() => {
        formRef
          .validate()
          .then(async () => {
            try {
              loading.value = true
              await marketingApi.updateGroupConfig(formModel.value)

              notification.success({
                message: '编辑活动配置成功',
                duration: 1.5
              })
            } finally {
              loading.value = false
            }
          })
          .catch(() => {})
      })
    }

    /** 初始化 */
    async function init() {
      try {
        loading.value = true

        const res = await marketingApi.getGroupConfig()

        Object.assign(formModel.value, res)

        fileList.value.indexPicture = [
          {
            uid: Math.random().toString().slice(-5),
            url: formModel.value.indexPicture
          }
        ]

        fileList.value.bannerPicture = [
          {
            uid: Math.random().toString().slice(-5),
            url: formModel.value.bannerPicture
          }
        ]

        editorConfig.value.editorHtml = res.groupRule
        editorConfig.value.editorVisible = true
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      init()
    })

    return {
      loading,
      formModel,
      formRef,
      editorRef,
      editorConfig,
      fileList,
      handleUploadChange,
      handleRemoveUpload,
      handleCancel,
      handleSubmit
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <Form labelCol={{ span: 3 }}>
            <FormItem label="总开关">
              <Switch
                v-model:checked={this.formModel.status}
                checkedValue={1}
                unCheckedValue={0}
              ></Switch>
            </FormItem>
            <FormItem
              label="拼团入口标题"
              {...this.formRef.validateInfos['title']}
            >
              <Input
                v-model:value={this.formModel.title}
                class={styles.formInput}
                placeholder="请输入"
              />
            </FormItem>
            <FormItem
              label="拼团入口图"
              {...this.formRef.validateInfos['indexPicture']}
            >
              <Upload
                action={commonApi.uploadFileUrl}
                accept="image/*"
                listType="picture-card"
                fileList={this.fileList.indexPicture}
                showUploadList={{
                  showPreviewIcon: false,
                  showRemoveIcon: true
                }}
                onChange={args => this.handleUploadChange('indexPicture', args)}
                remove={args => this.handleRemoveUpload('indexPicture', args)}
              >
                {!this.formModel.indexPicture ? (
                  <div>
                    <SvgIcon name="upload" />
                    <div class="ant-upload-text"></div>
                  </div>
                ) : null}
              </Upload>
              <span class={styles.formDesc}>注：建议尺寸750*960</span>
            </FormItem>
            <FormItem
              label="拼团首页宣传图"
              {...this.formRef.validateInfos['bannerPicture']}
            >
              <Upload
                action={commonApi.uploadFileUrl}
                accept="image/*"
                listType="picture-card"
                fileList={this.fileList.bannerPicture}
                showUploadList={{
                  showPreviewIcon: false,
                  showRemoveIcon: true
                }}
                onChange={args =>
                  this.handleUploadChange('bannerPicture', args)
                }
                remove={args => this.handleRemoveUpload('bannerPicture', args)}
              >
                {!this.formModel.bannerPicture ? (
                  <div>
                    <SvgIcon name="upload" />
                    <div class="ant-upload-text"></div>
                  </div>
                ) : null}
              </Upload>
              <span class={styles.formDesc}>注：建议尺寸750*608</span>
            </FormItem>
            <FormItem
              label="活动规则"
              {...this.formRef.validateInfos['groupRule']}
            >
              <ProEditor ref="editorRef" {...this.editorConfig} />
            </FormItem>
            <Divider />
            <FormItem class={styles.formBtns}>
              <Space>
                <Button class={styles.formBtn} onClick={this.handleCancel}>
                  取消
                </Button>
                <Button
                  class={styles.formBtn}
                  type="primary"
                  onClick={this.handleSubmit}
                >
                  保存
                </Button>
              </Space>
            </FormItem>
          </Form>
        </Spin>
      </div>
    )
  }
})
